package com.shop.thread.thread;


import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadPoolTest {

    AtomicInteger ctl = new AtomicInteger(0);

    public static void main(String[] args) {

        Object object = new Object();

        ExecutorService service = Executors.newFixedThreadPool(12);
        service.submit(()->System.out.println("11"));

        ExecutorService executorService = new ThreadPoolExecutor(10,15,1000*15,
                TimeUnit.MILLISECONDS,new LinkedBlockingQueue<>(20));
        executorService.submit(()->System.out.println(111));


        ThreadPoolTest threadPoolTest = new ThreadPoolTest();
        new Thread(()->{
            if (threadPoolTest.lock()){
                System.out.println(Thread.currentThread().getName() + "get this lock ...");
                try {
                    Thread.sleep(2 * 1000);
                } catch (InterruptedException e) {
                }finally {
                    System.out.println(Thread.currentThread().getName() + "release this lock ...");
                    threadPoolTest.release();
                }
            }else {
                System.out.println(Thread.currentThread().getName() + "is wait ...");
            }
        }).start();

        new Thread(()->{
            if (threadPoolTest.lock()){
                System.out.println(Thread.currentThread().getName() + "get this lock ...");
                try {
                    Thread.sleep(2 * 1000);
                } catch (InterruptedException e) {
                }finally {
                    System.out.println(Thread.currentThread().getName() + "release this lock ...");
                    threadPoolTest.release();
                }
            }else {
                System.out.println(Thread.currentThread().getName() + "is wait ...");
            }
        }).start();
    }

    public Boolean lock(){
        return ctl.compareAndSet(0,1);
    }

    public Boolean release(){
        return ctl.compareAndSet(1,0);
    }



}
